﻿using DevExpress.XtraEditors;
using Sunisoft.IrisSkin;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MusicPlayer
{
    public partial class MainForm : Form
    {
        #region 属性和构造函数
        private BackgroundWorker bgWorker1;//自动切换图片线程
        private BackgroundWorker bgWorker2;//显示歌词
        private string[] bgUrls;//图片Url
        private int curIndex = 0;//当前图片索引
        private bool isRunning = false;
        private string[] curLyric;
        private SkinEngine skinEngine;
        public MainForm()
        {
            InitializeComponent();
        }
        #endregion

        private void MainForm_Load(object sender, EventArgs e)
        {
            InitInfo();
            this.lblLyric.Parent = this.pbImage;

            //初始化歌曲列表
            List<MediaInfo> lstMedias = new List<MediaInfo>()
            {
                 new MediaInfo()
                 {
                    Id = "001",
                    Name = "一亿个伤心",
                    XPath = @"G:\muisc\雪儿 - 一亿个伤心 - 单曲版.mp3",
                    Lyric = @"G:\muisc\雪儿 - 一亿个伤心 - 单曲版.lrc",
                    XIcon=global::MusicPlayer.Properties.Resources.music
                }
            };

            this.bsMediaList.DataSource = lstMedias;
            this.dgMediaList.AutoGenerateColumns = false;
            this.dgMediaList.DataSource = this.bsMediaList;
            //
            this.dgHistory.AutoGenerateColumns = false;
            
            //初始化背后事件
            this.bgWorker1 = new BackgroundWorker();
            this.bgWorker1.WorkerSupportsCancellation = true;
            this.bgWorker1.DoWork += BgWorker1_DoWork;

            this.bgWorker2 = new BackgroundWorker();
            this.bgWorker2.WorkerSupportsCancellation = true;
            this.bgWorker2.DoWork += BgWorker2_DoWork;
            /*
              //this.bgUrls = new string[3] {
                "http://old.bz55.com/uploads/allimg/160322/139-1603221A304.jpg",
                "http://cimage.tianjimedia.com/uploadImages/thirdImages/2017/107/54XO1649NK8S.jpg",
                "http://pic1.win4000.com/wallpaper/f/549cf3e9be982.jpg"
             */
            //背景图列表           
            this.bgUrls = new string[1] {
                "http://p16.qhimg.com/bdr/__85/t01de7f2893a88af275.jpg"
            };
        }

        /// <summary>
        /// 初始化皮肤
        /// </summary>
        private void InitInfo()
        {
            this.skinEngine = new SkinEngine();
            this.skinEngine.SkinFile = AppDomain.CurrentDomain.BaseDirectory + @"Skins\MSN.ssk";
            this.skinEngine.DisableTag = 9999;
            ReadSkinFile();
        }

        /// <summary>
        /// 背景图切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BgWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while (isRunning)
            {
                if (bgUrls != null && bgUrls.Length > 0)
                {
                    this.curIndex = (this.curIndex % bgUrls.Length);
                    this.pbImage.Image = Image.FromStream(HttpWebRequest.Create(bgUrls[this.curIndex]).GetResponse().GetResponseStream());
                    this.pbImage.SizeMode = PictureBoxSizeMode.StretchImage;
                    this.curIndex++;
                    this.lblTime.Invoke(new Action(() =>
                    {
                        this.lblTime.Text = string.Format("{0}/{1}", this.axWindowsMediaPlayer1.Ctlcontrols.currentPositionString, this.axWindowsMediaPlayer1.currentMedia.durationString);
                        //this.lblTime.ForeColor = Color.White;
                    }));                  
                }
                Thread.Sleep(2000);
            }
        }

        /// <summary>
        /// 歌词显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BgWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            while (isRunning && this.curLyric!=null)
            {
                showLyric();
                Thread.Sleep(500);
            }
        }

        /// <summary>
        /// 歌曲列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgMediaList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                this.axWindowsMediaPlayer1.Ctlcontrols.stop();
                MediaInfo mi = this.dgMediaList.Rows[e.RowIndex].DataBoundItem as MediaInfo;
                this.axWindowsMediaPlayer1.URL = mi.XPath;
                //歌词
                ReadLyricFromFile(mi.Lyric);
                this.axWindowsMediaPlayer1.Ctlcontrols.play();
                //
                if (!this.bgWorker1.IsBusy)
                {
                    this.isRunning = true;
                    this.bgWorker1.RunWorkerAsync();
                }
                this.lblLyric.Text = mi.Name;
                if (!this.bgWorker2.IsBusy && this.curLyric!=null) {
                    this.isRunning = true;
                    this.bgWorker2.RunWorkerAsync();
                }
                if (!this.bsMediaHistory.Contains(mi))
                {
                    this.bsMediaHistory.Add(mi);
                }
               
            }
        }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("  确  定  退  出  ？  ", "提  示", MessageBoxButtons.YesNo, MessageBoxIcon.None) == DialogResult.Yes)
            {
                this.Cursor = Cursors.WaitCursor;
                this.Cursor = Cursors.Arrow;
                //System.Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
            }
            this.isRunning = false;
        }

        /// <summary>
        /// 播放状态改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {

        }

        /// <summary>
        /// 显示歌词
        /// </summary>
        private void showLyric()
        {
            try
            {
                if (this.curLyric != null && this.curLyric.Length > 0)
                {
                    double cur = this.axWindowsMediaPlayer1.Ctlcontrols.currentPosition;
                    double total = this.axWindowsMediaPlayer1.currentMedia.duration;
                    string curString = this.axWindowsMediaPlayer1.Ctlcontrols.currentPositionString;
                    int v = (int)Math.Ceiling((cur / total) * curLyric.Length);
                    string vi = string.Empty;
                    if (v < 15)
                    {
                        if (v < 5)
                        {
                            vi = string.Join("\n", this.curLyric, 0, 5);
                        }
                        else
                        {
                            //如果小于15条，则逐条显示
                            vi = string.Join("\n", this.curLyric, 0, v + 5);
                        }
                    }
                    else
                    {
                        //否则，只显示15条，感觉向上滚动。
                        vi = string.Join("\n", this.curLyric, v - 10, 15);
                    }
                    this.lblLyric.Invoke(new Action(() =>
                    {
                        this.lblLyric.Text = vi;
                    }));

                }
            }
            catch (Exception) { }
        }
        /// <summary>
        /// 从文件中读取歌词
        /// </summary>
        /// <param name="file"></param>
        public void ReadLyricFromFile(string file)
        {
            if (File.Exists(file))
            {
                using (FileStream fs = new FileStream(file, FileMode.Open))
                {
                    using (StreamReader sr = new StreamReader(fs, Encoding.Default))
                    {
                        string temp = sr.ReadToEnd();
                        string[] tempArr = temp.Split('\n');
                        this.curLyric = new string[tempArr.Length - 4];
                        for (int i = 4; i < tempArr.Length; i++)
                        {
                            int index = tempArr[i].IndexOf("]");
                            this.curLyric[i - 4] = index == -1 ? tempArr[i] : tempArr[i].Substring(tempArr[i].IndexOf("]") + 1);
                        }
                    }
                }
            }
            else
            {
                this.curLyric = null;
            }
        }

        private void btnMediaList_Click(object sender, EventArgs e)
        {
            this.dgMediaList.Visible = !this.dgMediaList.Visible;
        }

        private void btnHistory_Click(object sender, EventArgs e)
        {
            this.dgHistory.Visible = !this.dgHistory.Visible;
        }

        /// <summary>
        /// 读取皮肤文件
        /// </summary>
        private void ReadSkinFile()
        {
            string folder = AppDomain.CurrentDomain.BaseDirectory + "Skins";
            string[] files = Directory.GetFiles(folder);
            foreach (string file in files)
            {
                this.tdBtnSkins.DropDownItems.Add(Path.GetFileNameWithoutExtension(file), null, new EventHandler(tdBtnSkins_ItemClick));
            }

        }

        /// <summary>
        /// 换肤事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tdBtnSkins_ItemClick(object sender, EventArgs e)
        {
            string folder = AppDomain.CurrentDomain.BaseDirectory + "Skins";
            string name = sender.ToString();
            string skinFile = string.Format(@"{0}\{1}.ssk", folder, name);
            this.skinEngine.SkinFile = skinFile;
        }

        /// <summary>
        /// 添加本地歌曲
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.AddExtension = false;
            ofd.CheckFileExists = true;
            ofd.CheckPathExists = true;
            ofd.Tag = "请将歌词和音乐文件放在相同目录";
            ofd.Filter = "Audio文件(*.avi)|*.avi|WAV文件(*.wav)|*.wav |MP3文件(*.mp3)|*.mp3|所有文件(*.*)|*.* ";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                MediaInfo mi = new MediaInfo()
                {
                    Id = "002",
                    Name = Path.GetFileNameWithoutExtension(ofd.FileName),
                    XPath = ofd.FileName,
                    Lyric =Path.GetDirectoryName(ofd.FileName)+"\\"+ Path.GetFileNameWithoutExtension(ofd.FileName) + ".lrc",
                    XIcon = global::MusicPlayer.Properties.Resources.music
                };
                this.bsMediaList.Add(mi);
            }
        }

        /// <summary>
        /// 历史记录事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgHistory_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                this.axWindowsMediaPlayer1.Ctlcontrols.stop();
                MediaInfo mi = this.dgHistory.Rows[e.RowIndex].DataBoundItem as MediaInfo;
                this.axWindowsMediaPlayer1.URL = mi.XPath;
                //歌词
                ReadLyricFromFile(mi.Lyric);
                this.axWindowsMediaPlayer1.Ctlcontrols.play();
                //
                if (!this.bgWorker1.IsBusy)
                {
                    this.isRunning = true;
                    this.bgWorker1.RunWorkerAsync();
                }
                this.lblLyric.Text = mi.Name;
                if (!this.bgWorker2.IsBusy && this.curLyric != null)
                {
                    this.isRunning = true;
                    this.bgWorker2.RunWorkerAsync();
                }
                if (!this.bsMediaHistory.Contains(mi))
                {
                    this.bsMediaHistory.Add(mi);
                }
            }
        }
    }
}
